package com.ck.ck_back.service.impl;

import com.ck.ck_back.dao.ContentMapper;
import com.ck.ck_back.dao.UserMapper;
import com.ck.ck_back.pojo.Content;
import com.ck.ck_back.pojo.User;
import com.ck.ck_back.service.contentservice;
import com.ck.ck_back.utils.WordContext;
import com.ck.ck_back.utils.WordFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class contentserviceImpl implements contentservice {
    @Resource
    private ContentMapper contentMapper;
    @Resource
    private UserMapper userMapper;

    private final WordContext context = new WordContext();
    private final WordFilter filter = new WordFilter(context);

//    根据文章id拿文章
    @Override
    public Content selectbyid(int content_id) {
        Content content = contentMapper.selectByPrimaryKey(content_id);
        if (content!= null){
            return content;
        }else {return null;}
    }

    //    插入文章内容，并返回内容的id
//    40400：参数错误，30000无此人,20000此人身份错误，不然就是id
    @Transactional
    @Override
    public int insert_Content(String user_id, String content) {
        if (user_id !=null &&!user_id.equals("")&&content!=null&&!content.equals("")){
            User user = userMapper.selectByPrimaryKey(user_id);
            if (user != null){
                if (user.getIdentity() == true){
                    Content content_table = new Content();
                    content_table.setUserId(user_id);
                    String newcontent=filter.replace(content);
                    content_table.setContent(newcontent);
                    content_table.setConTime(new Date().getTime());
                    contentMapper.insertSelective(content_table);
                    List<Content> contents = contentMapper.selectByUserId(user_id);
//                    拿最新插入的id
                    return contents.get(0).getContentId();
                }else {return 200000;}
            }else {return 300000;}
        }else {return 404000;}
    }

//    //    根据id更新内容,404参数错误,3无此文章，先创建，2更新失败，1成功
    @Transactional
    @Override
    public int update(int content_id, String content) {
        if(!String.valueOf(content_id).equals("") && !content.equals("")&&content !=null){
            Content content1 = contentMapper.selectByPrimaryKey(content_id);
            if (content1!=null){
                content1.setContent(content);
                int result=contentMapper.updateByPrimaryKeySelective(content1);
                if (result == 1){
                    return result;
                }else {return 2;}
            }else {return 3;}
        }else {
            return 404;
        }
    }


}
